package com.miguo.framework.authorize;

import java.math.BigInteger;
import java.security.KeyFactory;
import java.security.PublicKey;
import java.security.spec.RSAPublicKeySpec;

import javax.crypto.Cipher;


public class RSA {

	public static String Key = "B664501BDFD73B634C8B07586B795150A1535F88C97C242A22DA482157189A81367EA88025A7347DF957862D05D824531F7F85807707B55804FF98457E165C0D55B69ED0A6009C0185C23DE0DEDD49AF27981208A21247A76E546A67EC52BCDC8AC960B24C06703F79578353B63F08CEB5C415E05BCDEB2F9ECB559D1FB302DF";

	private static final String exponent = "10001";
	
	private static final String ALGORITHM = "RSA";
	
	public static String Encrypt(String string) {
		int Len = string.length() / 16;
		String Data = "";
		for (int i = 0; i < Len; i++) {
			Data += EncryptHandle(string.substring(0, 16)) + "|";
			string = string.substring(16);
		}
		Data += EncryptHandle(string) + "|";
		return trim(Data, '|');
	}

	/**
	 * 使用公钥加密
	 * 
	 * @param string
	 * @return string
	 */
	private static String EncryptHandle(String string) {
		try {
			KeyFactory keyFactory = KeyFactory.getInstance(ALGORITHM);

			BigInteger n = new BigInteger(Key, 16);
			BigInteger e = new BigInteger(exponent, 16);
			RSAPublicKeySpec keySpec = new RSAPublicKeySpec(n, e);

			PublicKey PublicKey = (PublicKey) keyFactory.generatePublic(keySpec);
			
			Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
			cipher.init(Cipher.ENCRYPT_MODE, PublicKey);

			byte[] output = cipher.doFinal(string.getBytes("UTF-8"));

			String result = new String(Hex.encodeHex(output));

			//String result = BASE64.encode(output);

			return result;

		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * 去除字符串首尾出现的某个字符.
	 * 
	 * @param source
	 *            源字符串.
	 * @param element
	 *            需要去除的字符.
	 * @return String.
	 */
	private static String trim(String source, char element) {
		boolean beginIndexFlag = true;
		boolean endIndexFlag = true;
		do {
			int beginIndex = source.indexOf(element) == 0 ? 1 : 0;
			int endIndex = source.lastIndexOf(element) + 1 == source.length() ? source
					.lastIndexOf(element) : source.length();
			source = source.substring(beginIndex, endIndex);
			beginIndexFlag = (source.indexOf(element) == 0);
			endIndexFlag = (source.lastIndexOf(element) + 1 == source.length());
		} while (beginIndexFlag || endIndexFlag);
		return source;
	}

}
